package org.netwia.networks.nodes;

import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.netwia.networks.Node;
import org.netwia.utils.ValidationUtils;

/**
 * Implementation of node which multiplies input number by constant.
 * Only 1 input to this node is allowed.
 * 
 * @author radek.hecl
 */
public class DoubleConstMultiplyNode implements Node<Double> {

    /**
     * Builder object.
     */
    public static class Builder {

        /**
         * Factor for multiplication.
         */
        private Double factor;
        
        /**
         * Sets factor for multiplication.
         * 
         * @param factor factor for multiplication
         * @return this instance
         */
        public Builder setFactor(Double factor) {
            this.factor = factor;
            return this;
        }
        
        /**
         * Builds the result object.
         * 
         * @return created object
         */
        public DoubleConstMultiplyNode build() {
            return new DoubleConstMultiplyNode(this);
        }
    }

    /**
     * Factor for multiplication.
     */
    private Double factor;

    /**
     * Creates new instance.
     * 
     * @param builder builder object
     */
    public DoubleConstMultiplyNode(Builder builder) {
        factor = builder.factor;
        guardInvariants();
    }

    /**
     * Guards this object to be consistent. Throws exception if this is not the case.
     */
    private void guardInvariants() {
        ValidationUtils.guardNotNull(factor, "factor cannot be null");
    }

    @Override
    public Double process(Map<String, Double> inputs) {
        ValidationUtils.guardEquals(1, inputs.size(), "only 1 input is supported: inputs.keySet = " + inputs.keySet());
        for (String key : inputs.keySet()) {
            return inputs.get(key) * factor;
        }
        throw new RuntimeException("unknown situation, this is most likely bug in the source code");
    }
    
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}
